package com.cqie.tes.config;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cqie.tes.domain.RoleUser;
import com.cqie.tes.domain.SysRole;
import com.cqie.tes.domain.SysUser;
import com.cqie.tes.mapper.SysRoleMapper;
import com.cqie.tes.mapper.SysUserMapper;
import com.cqie.tes.service.RoleUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserService implements UserDetailsService {
    @Autowired
    RoleUserService roleUserService;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;
    /**
     * SpringSecurity 根据用户名查询用户
     * */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username+"->登录");
        // 检查
        if (StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 根据username查询user
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        MyUserDetile myUserDetile = new MyUserDetile();
        myUserDetile.setSysUser(sysUser);
        // 根据userid查询roleidList
        List<Long> ids = new ArrayList<>();
        QueryWrapper<RoleUser> roleUserQueryWrapper = new QueryWrapper<>();
        if (sysUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        roleUserQueryWrapper.eq("userId",sysUser.getId());
        List<RoleUser> roleUserList = roleUserService.list(roleUserQueryWrapper);
        roleUserList.forEach(roleUser->{
            ids.add(roleUser.getRoleId());
        });
        // 根据ROLEidList 查询role
        QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
        sysRoleQueryWrapper.in("id",ids);
        List<SysRole> sysRoleList = sysRoleMapper.selectList(sysRoleQueryWrapper);
        myUserDetile.setRoles(sysRoleList);
        // 查询完成，返回数据
        System.out.println("user->"+myUserDetile);
        return myUserDetile;
    }
}
